package ch.fusun.baron.weather;

/**
 * Makes the water fall from the sky :)
 */
public class WaterFallingDownUpdater implements AutomatonUpdater {

	private final int altitude;
	private final float WATER_FACTOR = 1f;

	/**
	 * Constructor
	 * 
	 * @param altitude
	 */
	public WaterFallingDownUpdater(int altitude) {
		this.altitude = altitude;
	}

	@Override
	public void update(Cube[][][] surroundingCubes, Cube cube) {
		float waterDiff = 0;
		Cube oldCube = surroundingCubes[1][1][1];
		for (Cube[][] surroundingCube : surroundingCubes) {
			for (Cube[] elements : surroundingCube) {
				for (Cube child : elements) {
					boolean topWrapAround = (child.getZ() == 0)
							&& (oldCube.getZ() == altitude - 1);
					boolean bottomWrapAround = (child.getZ() == altitude - 1)
							&& (oldCube.getZ() == 0);

					boolean wrapAround = topWrapAround && bottomWrapAround;
					// water
					if (!wrapAround) {
						if ((child.getX() == oldCube.getX())
								&& (child.getY() == oldCube.getY())) {
							if (child.getZ() > oldCube.getZ()) {
								waterDiff += WATER_FACTOR * child.getWater();
							}
							if (child.getZ() < oldCube.getZ()) {
								waterDiff -= WATER_FACTOR * oldCube.getWater();
							}
						}
					}
				}
			}
		}
		cube.setWater(oldCube.getWater() + waterDiff / 54.0f);
	}
}
